/*
 * =====================================================================================
 *
 *       Filename:  1-sort.cpp
 *
 *    Description:  第一章，排序问题
 *
 *        Version:  1.0
 *        Created:  2011-11-8 15:08:32
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  YOUR NAME (),
 *        Company:
 *
 * =====================================================================================
 */
#include "1-sort.h"

#include <iostream>
#include <fstream>
#include <iterator>
#include <ctime>
#include <cstring>
#include <string>

#include <boost/program_options.hpp>
namespace po = boost::program_options;

void quick_sort(const std::string &name)
{
    std::vector<int> A(MAX_INT);

    std::ifstream in(name.c_str());

    if (!in) {
        std::cout << "open file " << name << " failed." << std::endl;
    }

    int cnt = 0;

    while (in >> A[cnt++]) {
        ;
    }

    std::sort(A.begin(), A.begin() + cnt);

    std::string sname = name + "-quick-sort.stxt";
    std::ofstream file(sname.c_str());

    for (int i = 0; i < cnt; ++i) {
        file << A[i] << std::endl;
    }

    file.close();
}

void sort_file(const std::string &name)
{
    int cnt = MAX_INT / 8 + 1;
    char *A = new char[cnt];
    memset(A, 0, cnt * sizeof(char));

    std::ifstream in(name.c_str());

    if (!in) {
        std::cout << "open file " << name << " failed." << std::endl;
    }

    int tmp = 0;

    while (in >> tmp) {
        set_bit(A, tmp);
    }

    std::string sname = name + ".stxt";
    std::ofstream file(sname.c_str());

    for (int i = 0; i < MAX_INT; ++i) {
        if (bit(A, i)) {
            file << i << std::endl;
        }
    }

    file.close();

    delete [] A;
}

int main(int argc, const char *argv[])
{
    // Declare the supported options.
    po::options_description desc("Allowed options");
    desc.add_options()
    ("help", "sort no duplcate inter value")
    ("file", po::value<std::string>(), "set need to be sorted file")
    ;

    po::variables_map vm;
    po::store(po::parse_command_line(argc, argv, desc), vm);
    po::notify(vm);

    if (vm.count("help")) {
        std::cout << desc << "\n";
        return 1;
    }

    if (vm.count("file")) {
        std::string name = vm["file"].as<std::string>();
        std::cout << "file was set to " << name << ".\n";
        clock_t start = clock();
        quick_sort(name);
        std::cout << "the running time of quick_sort is " << (clock() - start) / CLOCKS_PER_SEC << std::endl;

        start = clock();
        sort_file(name);
        std::cout << "the running time of sort_file is " << (clock() - start) / CLOCKS_PER_SEC << std::endl;
    } else {
        std::cout << "file was not set.\n";
    }

    return 0;
}
